/**
 * Created by Richard on 17/9/14.
 */
/**
 * 便于统一处理请求和返回
 */

import axios from 'axios'
import Vue from 'vue';

let loadingNo = false;
export default class Axios {
  constructor () {
  };

  static init (conf) {
    // axios.defaults = conf;
    axios.defaults.baseURL = conf.baseURL;

    // 添加一个请求拦截器
    axios.interceptors.request.use(function (config) {
      loadingNo = false;
      if (!config.hideLoading) {
        loadingNo = true;
        Vue.$vux.loading.show();
      }
      //标识为ajax异步请求
      config.headers["X-Requested-With"] = "XMLHttpRequest";

      if (conf && conf.baseURL) {
        config.baseURL = conf.baseURL;
      }
      return config;
    }, function (error) {
      Vue.$vux.loading.hide();
      return Promise.reject(error);
    });

    // 添加一个响应拦截器
    axios.interceptors.response.use(function (response) {
      if (loadingNo) {
        Vue.$vux.loading.hide();
      }
      if (response.status === 200 && response.data.code === "OK") {
        return response.data;
      } else {
        return Promise.reject(response.data);
      }
    }, function (error) {
      Vue.$vux.loading.hide();
      if (error.response.status === 401 || error.response.status === 403) {
        // iView.Message.info("尚未登录，请先登录!");
        if (!conf && !conf.unauthorizedUrl) {
          window.location.href = conf.unauthorizedUrl;
        }
      }
      return Promise.reject(error.response.data);
    });
  }
};
